package com.example.basecomponent.cityPicker;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.basecomponent.R;
import com.example.basecomponent.TipDialog;
import com.example.basecomponent.cityPicker.adapter.CityListAdapter;
import com.example.basecomponent.cityPicker.adapter.InnerListener;
import com.example.basecomponent.cityPicker.adapter.OnPickListener;
import com.example.basecomponent.cityPicker.adapter.decoration.DividerItemDecoration;
import com.example.basecomponent.cityPicker.adapter.decoration.SectionItemDecoration;
import com.example.basecomponent.cityPicker.model.City;
import com.example.basecomponent.cityPicker.model.HotCity;
import com.example.basecomponent.cityPicker.model.LocatedCity;
import com.example.basecomponent.cityPicker.util.ScreenUtil;
import com.example.basecomponent.cityPicker.view.SideIndexBar;
import java.util.ArrayList;
import java.util.List;

//区域多选
public class CityMultipleChoiceFragment extends Fragment implements TextWatcher,
        View.OnClickListener, SideIndexBar.OnIndexTouchedChangedListener, InnerListener {


    private View mContentView;
    private RecyclerView mRecyclerView;
    private View mEmptyView;
    private TextView mOverlayTextView;
    private SideIndexBar mIndexBar;
    private EditText mSearchBox;
    private TextView mCancelBtn;
    private ImageView mClearAllBtn;

    private LinearLayoutManager mLayoutManager;
    private CityListAdapter mAdapter;
    private List<City> mAllCities;
    private List<HotCity> mHotCities;
    private List<City> mResults;

    private LocatedCity mLocatedCity;
    private int locateState;
    private OnPickListener mOnPickerListener;
    private JsonParseUtil mJsonParesUtil;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_city_multiple_choice, container, false);
        return mContentView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    private void initViews() {
        mRecyclerView = mContentView.findViewById(R.id.cp_city_recyclerview);
        mLayoutManager = new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new SectionItemDecoration(getActivity(), mAllCities), 0);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity()), 1);
        mAdapter = new CityListAdapter(getActivity(), mAllCities, mHotCities, locateState);
        mAdapter.autoLocate(true);
        mAdapter.setInnerListener(this);
        mAdapter.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                //确保定位城市能正常刷新
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mAdapter.refreshLocationItem();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            }
        });

        mEmptyView = mContentView.findViewById(R.id.cp_empty_view);
        mOverlayTextView = mContentView.findViewById(R.id.cp_overlay);

        mIndexBar = mContentView.findViewById(R.id.cp_side_index_bar);
        mIndexBar.setNavigationBarHeight(ScreenUtil.getNavigationBarHeight(getActivity()));
        mIndexBar.setOverlayTextView(mOverlayTextView)
                .setOnIndexChangedListener(this);

        mSearchBox = mContentView.findViewById(R.id.cp_search_box);
        mSearchBox.addTextChangedListener(this);

        mCancelBtn = mContentView.findViewById(R.id.cp_cancel);
        mClearAllBtn = mContentView.findViewById(R.id.cp_clear_all);
        mCancelBtn.setOnClickListener(this);
        mClearAllBtn.setOnClickListener(this);
    }

    private void initData() {
        //初始化热门城市
        if (mHotCities == null || mHotCities.isEmpty()) {
            mHotCities = new ArrayList<>();
//            mHotCities.add(new HotCity("苏州市", "suzhou", "320500"));
            /*mHotCities.add(new HotCity("上海市", "shanghai", "310100"));
            mHotCities.add(new HotCity("北京市", "beijing", "110100"));
            mHotCities.add(new HotCity("广州市", "guangzhou", "440100"));
            mHotCities.add(new HotCity("成都市", "chengdu", "510100"));
            mHotCities.add(new HotCity("三亚市", "sanya", "460200"));
            mHotCities.add(new HotCity("杭州市", "hangzhou", "330100"));
            mHotCities.add(new HotCity("西安市", "xian", "610100"));
            mHotCities.add(new HotCity("南京市", "nanjing", "320100"));
            mHotCities.add(new HotCity("厦门市", "xiamen", "350200"));*/
        }

        //初始化定位城市，默认为空时会自动回调定位
//        if (mLocatedCity == null) {
//            mLocatedCity = new LocatedCity(getString(R.string.cp_locating), "未知", "0");
//            locateState = LocateState.LOCATING;
//        } else {
//            locateState = LocateState.SUCCESS;
//        }
        mJsonParesUtil = new JsonParseUtil();
        new CityAsyncTask().execute(getActivity());
    }

    private class CityAsyncTask extends AsyncTask<Context, ProgressBar, List<City>> {

        private final TipDialog progressDialog;

        CityAsyncTask() {
            progressDialog = new TipDialog.Builder(getActivity())
                    .setIconType(TipDialog.Builder.ICON_TYPE_LOADING)
                    .setTipWord("正在加载")
                    .create();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.show();
        }

        @Override
        protected List<City> doInBackground(Context... context) {
            return mJsonParesUtil.getAllCities(context[0]);
        }

        @Override
        protected void onPostExecute(List<City> cities) {
            super.onPostExecute(cities);
            mAllCities = cities;
            //mAllCities.add(0, mLocatedCity);
//            mAllCities.add(0, new HotCity("热门城市", "未知", "0"));
            mResults = mAllCities;
            initViews();
            progressDialog.dismiss();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String keyword = s.toString();
        if (TextUtils.isEmpty(keyword)) {
            mClearAllBtn.setVisibility(View.GONE);
            mEmptyView.setVisibility(View.GONE);
            mResults = mAllCities;
            ((SectionItemDecoration) (mRecyclerView.getItemDecorationAt(0))).setData(mResults);
            mAdapter.updateData(mResults);
        } else {
            mClearAllBtn.setVisibility(View.VISIBLE);
            //开始查找
            mResults = mJsonParesUtil.searchCity(keyword);
            ((SectionItemDecoration) (mRecyclerView.getItemDecorationAt(0))).setData(mResults);
            if (mResults == null || mResults.isEmpty()) {
                mEmptyView.setVisibility(View.VISIBLE);
            } else {
                mEmptyView.setVisibility(View.GONE);
                mAdapter.updateData(mResults);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.cp_cancel) {
            if (mOnPickerListener != null) {
                mOnPickerListener.onCancel();
            }
            hideAndFinish();
        } else if (id == R.id.cp_clear_all) {
            mSearchBox.setText("");
        }
    }

    @Override
    public void onIndexChanged(String index, int position) {
        mAdapter.scrollToSection(index);
    }

    private void hideAndFinish() {
        if (getActivity() != null) {
            hideSoftInput();
            mSearchBox.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getActivity().finish();
                }
            }, 80);
        }
    }

    @Override
    public void dismiss(int position, City data) {
        if (mOnPickerListener != null) {
            mOnPickerListener.onPick(position, data);
        }
//        hideAndFinish();
    }

    public void hideSoftInput() {
        InputMethodManager imm =
                (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) return;
        imm.hideSoftInputFromWindow(mSearchBox.getWindowToken(), 0);
    }

    @Override
    public void locate() {
        if (mOnPickerListener != null) {
            mOnPickerListener.onLocate();
        }
    }

    public void setOnPickerListener(OnPickListener listener) {
        this.mOnPickerListener = listener;
    }

    public void locationChanged(LocatedCity location, int state) {
        mAdapter.updateLocateState(location, state);
    }

    public void setLocatedCity(LocatedCity location) {
        mLocatedCity = location;
    }

    public void setHotCities(List<HotCity> data) {
        if (data != null && !data.isEmpty()) {
            this.mHotCities = data;
            mAdapter.updateHotCities(data);
        }
    }
}
